import imghdr

from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import pandas as pd
from .models import Position, Question, Answer, Product
from .serializers import PositionSerializer, QuestionSerializer, AnswerSerializer, ProductSerializer
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.permissions import AllowAny
from rest_framework.pagination import PageNumberPagination


class PositionListCreateAPIView(APIView):
    parser_classes = [MultiPartParser, FormParser]

    def get(self, request):
        page_number = request.query_params.get('page', 1)  # 获取查询参数中的页数，默认为第一页
        page_size = request.query_params.get('pageSize', 10)  # 获取查询参数中的每页显示的数据量，默认为10
        paginator = PageNumberPagination()
        paginator.page_size = page_size
        positions = Position.objects.all()
        result_page = paginator.paginate_queryset(positions, request)
        serializer = PositionSerializer(result_page, many=True)
        return paginator.get_paginated_response(serializer.data)

    def post(self, request):
        serializer = PositionSerializer(data=request.data)
        serializer.fields['position_intro_link'].required = False
        serializer.fields['culture_highlight_link'].required = False
        serializer.fields['video_more_link'].required = False
        serializer.fields['image_more_link'].required = False
        serializer.fields['exhibition_outline_link'].required = False
        serializer.fields['video_path'].required = False
        serializer.fields['video_path'].required = False
        serializer.fields['exhibition_outline'].required = False
        serializer.fields['culture_highlight'].required = False
        serializer.fields['coordinate'].required = False
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            print(serializer.errors)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class PositionRetrieveUpdateDestroyAPIView(APIView):
    def get_object(self, pk):
        try:
            return Position.objects.get(pk=pk)
        except Position.DoesNotExist:
            raise status.HTTP_404_NOT_FOUND

    def get(self, request, pk):
        position = self.get_object(pk)
        serializer = PositionSerializer(position)
        return Response(serializer.data)

    def put(self, request, pk):
        position = self.get_object(pk)

        # Extract only the fields to be updated
        update_data = {
            'position_name': request.data.get('position_name'),
            'province': request.data.get('province'),
            'district': request.data.get('district'),
            'status': request.data.get('status'),
            'position_intro': request.data.get('position_intro'),
            'position_intro_link': request.data.get('position_intro_link'),
            'culture_highlight': request.data.get('culture_highlight'),
            'culture_highlight_link': request.data.get('culture_highlight_link'),
            'video_more_link': request.data.get('video_more_link'),
            'reservation_method': request.data.get('reservation_method'),
            'visit_duration': request.data.get('visit_duration'),
            'position_address': request.data.get('position_address'),
            'image_more_link': request.data.get('image_more_link'),
            'exhibition_outline': request.data.get('exhibition_outline'),
            'exhibition_outline_link': request.data.get('exhibition_outline_link'),
            'coordinate': request.data.get('coordinate'),
        }

        # Update image and video fields only if files are provided in the request
        if 'image_path' in request.FILES:
            update_data['image_path'] = request.FILES['image_path']
        if 'video_path' in request.FILES:
            update_data['video_path'] = request.FILES['video_path']
        serializer = PositionSerializer(position, data=update_data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        position = self.get_object(pk)
        position.delete()
        return Response(status=status.HTTP_200_OK)


class PositionListAPIView(APIView):
    permission_classes = [AllowAny]

    def get(self, request):
        positions = Position.objects.all()
        serializer = PositionSerializer(positions, many=True)
        return Response(serializer.data)


class ExcelUploadAPIView(APIView):
    field_mapping = {
        '阵地名': 'position_name',
        '阵地所在省份': 'province',
        '阵地所在区': 'district',
        '状态': 'status',
        '上传人': 'uploader',
        '修改人': 'modifier',
        '阵地简介': 'position_intro',
        '阵地简介详细链接': 'position_intro_link',
        '廉洁文化亮点': 'culture_highlight',
        '廉洁文化亮点详细链接': 'culture_highlight_link',
        '视频作品路径': 'video_path',
        '视频作品更多链接': 'video_more_link',
        '预约方式': 'reservation_method',
        '参观时长': 'visit_duration',
        '阵地地址': 'position_address',
        '图片路径': 'image_path',
        '图片更多链接': 'image_more_link',
        '展陈大纲': 'exhibition_outline',
        '展陈大纲详细链接': 'exhibition_outline_link',
        '坐标': 'coordinate',
    }

    def post(self, request):
        file = request.FILES.get('file')
        if file is None:
            return Response({'error': '请上传文件'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            df = pd.read_excel(file)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        # Rename columns based on field mapping
        df = df.rename(columns=self.field_mapping)

        serializer_errors = []
        for index, row in df.iterrows():
            serializer = PositionSerializer(data=row.to_dict())
            if serializer.is_valid():
                serializer.save()
            else:
                serializer_errors.append(serializer.errors)

        if serializer_errors:
            return Response({'errors': serializer_errors}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'message': '文件上传成功'}, status=status.HTTP_201_CREATED)


# 获取所有问题和答案
class QuestionListWithAnswersAPIView(APIView):
    permission_classes = [AllowAny]

    def get(self, request):
        # 获取所有问题
        questions = Question.objects.all()
        # 构建问题及答案数组的字典
        questions_with_answers = []

        for question in questions:
            # 获取该问题关联的所有答案
            answers = question.answer_set.all()

            # 构建问题及答案的字典
            question_data = {
                'id': question.id,
                'text': question.text,
                'question_type': question.question_type,
                'answers': [{'id': answer.id, 'text': answer.text, 'is_correct': answer.is_correct} for answer in
                            answers]
            }

            # 添加到问题及答案数组中
            questions_with_answers.append(question_data)
        return Response(questions_with_answers)


class RandomQuestionListAPIView(APIView):
    permission_classes = [AllowAny]

    def get(self, request):
        # 随机获取二十条问题
        questions = Question.objects.order_by('?')[:20]

        # 构建问题及答案数组的字典
        questions_with_answers = []

        for question in questions:
            # 获取该问题关联的所有答案
            answers = question.answer_set.all()

            # 构建问题及答案的字典
            question_data = {
                'id': question.id,
                'text': question.text,
                'question_type': question.question_type,
                'answers': [{'id': answer.id, 'text': answer.text, 'is_correct': answer.is_correct} for answer in
                            answers]
            }

            # 添加到问题及答案数组中
            questions_with_answers.append(question_data)

        return Response(questions_with_answers, status=status.HTTP_200_OK)


# 上传问题和答案
class QuestionAndAnswerCreateAPIView(APIView):
    def post(self, request):
        question = request.data.get('question')
        serializer = QuestionSerializer(data=question)
        if serializer.is_valid():
            question = serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 删除问题和答案
class QuestionAndAnswerDeleteAPIView(APIView):
    def delete(self, request, question_id):
        try:
            question = Question.objects.get(id=question_id)
        except Question.DoesNotExist:
            return Response({'error': '问题不存在'}, status=status.HTTP_404_NOT_FOUND)

        question.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


class ProductList(APIView):
    """
    List all products or create a new product.
    """

    def get(self, request, format=None):
        products = Product.objects.all()
        serializer = ProductSerializer(products, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = ProductSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class ProductDetail(APIView):
    """
    Retrieve, update or delete a product instance.
    """

    def get_object(self, pk):
        try:
            return Product.objects.get(pk=pk)
        except Product.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        product = self.get_object(pk)
        serializer = ProductSerializer(product)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        product = self.get_object(pk)
        data = request.data.copy()

        # 检查 image 字段是否为文件
        if 'image' not in request.FILES:
            data.pop('image')

        serializer = ProductSerializer(product, data=data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        product = self.get_object(pk)
        product.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
